﻿using System;
using System.Collections.Generic;
using System.Text;
using UmlDesigner.Gui;
using System.Diagnostics;

namespace UmlDesigner.Model.WorkUnits
{

    internal class DeleteItemWorkUnit : CompositeWorkUnit
    {

        internal DeleteItemWorkUnit(ItemWidget target, Document currentDocument)
        {
            item = target;

            // Any links attached to this item also need to be deleted.
            List<LinkWidget> linksToDelete = item.GetAllLinks();

            // If the item was part of a link, it also needs to be deleted.
            foreach (ItemWidget i in currentDocument.items)
            {
                if (i.IsLink())
                {
                    LinkWidget link = (LinkWidget)i;
                    if (link.GetDestination() == item || link.GetSource() == item)
                    {
                        linksToDelete.Add(link);
                    }
                }
            }

            foreach (LinkWidget link in linksToDelete)
            {
                AddItem(new DeleteItemWorkUnit(link, currentDocument));
            }

        }

        private ItemWidget item;
     
        #region IWorkUnit Members

        public override void Do(UmlControl umlControl)
        {
            base.Do(umlControl);

            Document currentDocument = umlControl.currentDocument;

            // Delete the item from the document.
            if (currentDocument.items.Contains(item))
            {
                currentDocument.items.Remove(item);
            }

            // If it was a link, remove it from the links on the source class.
            if (item.IsLink())
            {
                LinkWidget link = (LinkWidget)item;
                link.GetSource().RemoveLink(link);
                link.GetDestination().RemoveDestLink(link);

                link.DeallocateSlots();
            }
        }

        public override void Undo(UmlControl umlControl)
        {
            Document currentDocument = umlControl.currentDocument;

            // Delete the item from the document.
            if (!currentDocument.items.Contains(item))
            {
                currentDocument.items.Add(item);
            }

            // If it was a link, remove it from the links on the source class.
            if (item.IsLink())
            {
                LinkWidget link = (LinkWidget)item;
                link.GetSource().AddLinkToDest(link);
                link.GetDestination().AddLinkFromSource(link);

                link.AllocateSlots();
            }

            base.Undo(umlControl);
        }

        #endregion
    }
}
